package lk.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lk.model.LoginUser;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * author lk
 *
 * @date 2021/10/27 11:10
 * @description 使用简单的 用户名密码  json形式的方式进行登陆
 * @since 1.0
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    private static final String METHOD = "POST";

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!METHOD.equals(request.getMethod()) || !request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            throw new AuthenticationServiceException("请求方式或者请求格式错误");
        }
        // 获取到请求中用户名和密码
        LoginUser loginUser = null;
        try {
            loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                loginUser.getUsername(), loginUser.getPassword());
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
